package com.github.postsanf.yinian.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.ElseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.entity.YNLoginResponse;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.huanxin.db.DemoDBManager;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.DoSecretUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.LinkedHashMap;
import java.util.Map;

public class LoginActivity extends ElseActivity implements View.OnClickListener {
    private ImageView iv_cloud_1;
    private ImageView iv_cloud_2;
    private ImageView iv_cloud_3;
    private ImageView iv_cloud_4;
    private ImageView iv_cloud_5;
    private EditText et_login_username;
    private EditText et_login_password;
    private ImageView iv_login_back;
    private TextView tv_forget_password_back;
    private ProgressDialog mProgressDialog;
    private String username;
    private String password;
    private String userid = "";
    private String huanxinpassword = "";
    // 老用户微信绑定
    private UMShareAPI mShareAPI = null;
    private SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
    private RelativeLayout rl_login_back;
    private ImageView iv_return_white_login;
    private ImageView iv_stars1;
    private ImageView iv_stars2;
    private ImageView iv_stars3;
    private ImageView iv_stars4;
    private ImageView iv_stars5;
    private ImageView iv_stars6;
    private TextView tv_wx_login_back;
    private int mBackKeyPressedTimes = 0;
    private LinearLayout ll_bg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        registerBroadcast();
        initView();
    }

    private void registerBroadcast() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseactivity);
        myIntentFilter.addAction(ACTIONs.Exit);
        registerReceiver(MYReceiver, myIntentFilter);
    }

    private void initView() {
        iv_cloud_1 = ((ImageView) findViewById(R.id.iv_cloud_1));
        iv_cloud_2 = ((ImageView) findViewById(R.id.iv_cloud_2));
        iv_cloud_3 = ((ImageView) findViewById(R.id.iv_cloud_3));
        iv_cloud_4 = ((ImageView) findViewById(R.id.iv_cloud_4));
        iv_cloud_5 = ((ImageView) findViewById(R.id.iv_cloud_5));
        rl_login_back = ((RelativeLayout) findViewById(R.id.rl_login_back));
        et_login_username = (EditText) findViewById(R.id.et_login_username);
        et_login_password = ((EditText) findViewById(R.id.et_login_password));
        iv_login_back = ((ImageView) findViewById(R.id.iv_login_back));
        ll_bg = (LinearLayout) findViewById(R.id.ll_bg);
        //点击空白区域隐藏键盘
        ll_bg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ll_bg.setFocusable(true);
                ll_bg.setFocusableInTouchMode(true);
                ll_bg.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(LoginActivity.this.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                return false;
            }
        });
        tv_forget_password_back = ((TextView) findViewById(R.id.tv_forget_password_back));
        tv_forget_password_back.setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        tv_wx_login_back = ((TextView) findViewById(R.id.tv_wx_login_back));
        tv_wx_login_back.setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        iv_return_white_login = ((ImageView) findViewById(R.id.iv_return_white_login));
        iv_stars1 = ((ImageView) findViewById(R.id.iv_stars1));
        iv_stars2 = ((ImageView) findViewById(R.id.iv_stars2));
        iv_stars3 = ((ImageView) findViewById(R.id.iv_stars3));
        iv_stars4 = ((ImageView) findViewById(R.id.iv_stars4));
        iv_stars5 = ((ImageView) findViewById(R.id.iv_stars5));
        iv_stars6 = ((ImageView) findViewById(R.id.iv_stars6));
        iv_login_back.setOnClickListener(this);
        tv_forget_password_back.setOnClickListener(this);
        rl_login_back.setOnClickListener(this);
        iv_return_white_login.setOnClickListener(this);
        tv_wx_login_back.setOnClickListener(this);
        initAnimation();
        mProgressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        mProgressDialog.setTitle("");
        mProgressDialog.setMessage(CommonConstants.TIP_LOAD_LOGIN);
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

    private void initAnimation() {
        // 平移
        ObjectAnimator ta1 = ObjectAnimator.ofFloat(iv_cloud_1, "translationX", 0, 140);
        ta1.setDuration(10000);
        ta1.setRepeatCount(Animation.INFINITE);
        ta1.setRepeatMode(ValueAnimator.REVERSE);
        ta1.start();
        ObjectAnimator ta2 = ObjectAnimator.ofFloat(iv_cloud_2, "translationX", 0, 140);
        ta2.setDuration(10000);
        ta2.setRepeatCount(Animation.INFINITE);
        ta2.setRepeatMode(ValueAnimator.REVERSE);
        ta2.start();
        ObjectAnimator ta3 = ObjectAnimator.ofFloat(iv_cloud_3, "translationX", 0, 140);
        ta3.setDuration(10000);
        ta3.setRepeatCount(Animation.INFINITE);
        ta3.setRepeatMode(ValueAnimator.REVERSE);
        ta3.start();
        ObjectAnimator ta4 = ObjectAnimator.ofFloat(iv_cloud_4, "translationX", 0, 140);
        ta4.setDuration(10000);
        ta4.setRepeatCount(Animation.INFINITE);
        ta4.setRepeatMode(ValueAnimator.REVERSE);
        ta4.start();
        ObjectAnimator ta5 = ObjectAnimator.ofFloat(iv_cloud_5, "translationX", 0, 140);
        ta5.setDuration(10000);
        ta5.setRepeatCount(Animation.INFINITE);
        ta5.setRepeatMode(ValueAnimator.REVERSE);
        ta5.start();
        ObjectAnimator aa1 = ObjectAnimator.ofFloat(iv_stars1, "alpha", 0.2f, 2.0f);
        aa1.setDuration(1000);
        aa1.setRepeatCount(Animation.INFINITE);
        aa1.setRepeatMode(ValueAnimator.REVERSE);
        aa1.start();
        ObjectAnimator aa2 = ObjectAnimator.ofFloat(iv_stars2, "alpha", 0.2f, 2.0f);
        aa2.setDuration(1000);
        aa2.setRepeatCount(Animation.INFINITE);
        aa2.setRepeatMode(ValueAnimator.REVERSE);
        aa2.start();
        ObjectAnimator aa3 = ObjectAnimator.ofFloat(iv_stars3, "alpha", 0.2f, 2.0f);
        aa3.setDuration(1000);
        aa3.setRepeatCount(Animation.INFINITE);
        aa3.setRepeatMode(ValueAnimator.REVERSE);
        aa3.start();
        ObjectAnimator aa4 = ObjectAnimator.ofFloat(iv_stars4, "alpha", 0.2f, 2.0f);
        aa4.setDuration(1000);
        aa4.setRepeatCount(Animation.INFINITE);
        aa4.setRepeatMode(ValueAnimator.REVERSE);
        aa4.start();
        ObjectAnimator aa5 = ObjectAnimator.ofFloat(iv_stars5, "alpha", 0.2f, 2.0f);
        aa5.setDuration(1000);
        aa5.setRepeatCount(Animation.INFINITE);
        aa5.setRepeatMode(ValueAnimator.REVERSE);
        aa5.start();
        ObjectAnimator aa6 = ObjectAnimator.ofFloat(iv_stars6, "alpha", 0.2f, 2.0f);
        aa6.setDuration(1000);
        aa6.setRepeatCount(Animation.INFINITE);
        aa6.setRepeatMode(ValueAnimator.REVERSE);
        aa6.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_login_back:
                doLogin();
                break;
            case R.id.rl_login_back:
                DisplayUtils.setFoucs(rl_login_back);
                break;
            case R.id.tv_forget_password_back:
                intent2Activity(CheckPhoneActivity.class);
                break;
            case R.id.iv_return_white_login:
                startActivity(new Intent(this, LoginWeChatActivity.class));
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;
            case R.id.tv_wx_login_back:
                intent2Activity(LoginWeChatActivity.class);
                overridePendingTransition(R.anim.slide_up_in, R.anim.none_out);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (mBackKeyPressedTimes == 0) {
            showToast("再按一次退出程序 ");
            mBackKeyPressedTimes = 1;
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        mBackKeyPressedTimes = 0;
                    }
                }
            }.start();
            return;
        } else {
            sendBroadcast(new Intent(ACTIONs.Exit));
        }
        super.onBackPressed();
    }

    //登陆执行程序
    private void doLogin() {
        if (checkInput()) {
            mProgressDialog.show();
            String UMENG_CHANNEL = SystemUtils.getAppStoreName(LoginActivity.this, "UMENG_CHANNEL");
            LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
            mParam.put(CommonConstants.YNS_USERNAME, username);
            mParam.put(CommonConstants.YNS_PASSWORD, password);
            mParam.put(CommonConstants.YNS_CHANELSOURCE, UMENG_CHANNEL);
            StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynLogin))
                    .setMethod(HttpMethods.Post)
                    .setParamMap(mParam)
                    .setHttpListener(new HttpListener<String>(true, false, true) {
                        @Override
                        public void onSuccess(String s, Response<String> response) {
                            YNLoginResponse resLogin = gson.fromJson(s, YNLoginResponse.class);
                            Log.i("xjs", "login+s===>" + s);
                            if (resLogin != null && ReqUtils.isSuccess(resLogin.getCode())) {
                                // 存入录数据
                                SharedPreferences.Editor ed = application.getSp_login().edit();
                                ed.putString(getString(R.string.SP_YNS_USERNAME), DoSecretUtils.doSecretStr(username));
                                ed.putString(getString(R.string.SP_YNS_PASSWORD), DoSecretUtils.doSecretStr(password));
                                ed.putString(getString(R.string.LID), DoSecretUtils.doSecretStr(String.valueOf(resLogin.getData().get(0).getUserid())));
                                ed.commit();
                                application.setCurID(resLogin.getData().get(0).getUserid());
                                userid = String.valueOf(resLogin.getData().get(0).getUserid());
                                try {
                                    huanxinpassword = YNInviteSecret.decryptDES(String.valueOf(resLogin.getData().get(0).getPassword()), getResources().getString(R.string.UNKNOW_ID));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                switch (resLogin.getData().get(0).getIsBindWechat()) {
                                    // 未绑定微信
                                    case 0:
                                        if (!SystemUtils.isWeixinAvilible(LoginActivity.this)) {
                                            doLoginHuanXin(userid, huanxinpassword);
                                            return;
                                        }
                                        doLoginHuanXin(userid, huanxinpassword);
                                        // mShareAPI.doOauthVerify(LoginActivity.this, platform, umAuthListener);
                                        break;
                                    // 已绑定微信
                                    case 1:
                                        doLoginHuanXin(userid, huanxinpassword);
                                        break;
                                }
                            } else {
                                showToast(resLogin.getMsg());
                                mProgressDialog.dismiss();
                            }
                        }

                        @Override
                        public void onFailure(HttpException e, Response<String> response) {
                            showToast(getString(R.string.YN_NET_LINK));
                            mProgressDialog.dismiss();
                        }
                    });
            liteHttp.executeAsync(req);
        }
    }

    private void doLoginHuanXin(String currentUsername, String currentPassword) {
        DemoDBManager.getInstance().closeDB();
        DemoHelper.getInstance().setCurrentUserName(currentUsername);
        EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
                        BaseApplication.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
                CloseMainActivity();
                mProgressDialog.dismiss();
                intent2Activity(MainActivity.class);
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.i("LoginActivity", "login: onProgress");
            }

            @Override
            public void onError(final int code, final String message) {
                Log.i("LoginActivity", "login: onError: " + code);
                runOnUiThread(new Runnable() {
                    public void run() {
                        mProgressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    //判断输入
    private boolean checkInput() {
        username = et_login_username.getText().toString().trim();
        password = et_login_password.getText().toString().trim();
        if (username.length() <= 0) {
            showToast(CommonConstants.TIP_INPUT_USERNAME);
            setFocus(et_login_username);
            return false;
        }
        if (password.length() < 6) {
            showToast(CommonConstants.TIP_ERROR_PASSWORD);
            setFocus(et_login_password);
            return false;
        }
        return true;
    }

    // 重置焦点
    private void setFocus(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();
        et.findFocus();
    }


    // 授权监听
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            getUserInfo(platform);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            mProgressDialog.dismiss();
            showToast(getString(R.string.Wx_failed));
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            mProgressDialog.dismiss();
        }

    };

    // 获取用户信息
    private void getUserInfo(SHARE_MEDIA platform) {
        mShareAPI.getPlatformInfo(LoginActivity.this, platform,
                new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        String openid = map.get(CommonConstants.PARAM_OPENID);
                        doBindWeChat(openid, userid);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        mProgressDialog.dismiss();
                    }
                });
    }

    // 老用户绑定微信
    private void doBindWeChat(String openid, final String userid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_OPENID, openid);
        mParam.put(CommonConstants.YNS_USER_ID, userid);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynBindWeChat))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resBind = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resBind.getCode())) {
                            showToast("绑定成功");
//                            SnackBarUtils.makeShort(rl_login,"绑定成功").show();
                        } else {
                            showToast("绑定失败");
//                            SnackBarUtils.makeShort(rl_login,"绑定失败").show();
                        }
                        doLoginHuanXin(userid, huanxinpassword);
                    }

                    @Override
                    public void onEnd(Response<String> response) {
                        super.onEnd(response);
                        CloseMainActivity();
                        mProgressDialog.dismiss();
                        intent2Activity(MainActivity.class);
                        finish();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(getString(R.string.YN_NET_LINK));
                        CloseMainActivity();
                        mProgressDialog.dismiss();
                        intent2Activity(MainActivity.class);
                        finish();
                    }
                });
        liteHttp.executeAsync(req);
    }

    BroadcastReceiver MYReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(ACTIONs.actionCloseactivity, intent.getAction())) {
                finish();
            }
            if (TextUtils.equals(ACTIONs.Exit, intent.getAction())) {
                finish();
            }
        }
    };

    private void CloseMainActivity() {
        if (getSharedPreferences("OURINFO", MODE_PRIVATE).getBoolean("active", false)) {
            if (MainActivity.myMainActivity != null && !MainActivity.myMainActivity.isFinishing()) {
                MainActivity.myMainActivity.finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(MYReceiver);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
